<template>
  <Container v-resize:throttle.30="onResize">
    <!-- required -->
    <Cricle slot="center" :data-id="ids.center">
      <slot name="center"></slot>
    </Cricle>
    <!-- optional -->
    <Window 
      v-for="key in existSlots"
      :key="key"
      :data-id="ids[key]"
      :slot="key"
      :count="get(data, key, 'count') || 0"
      :color="get(data, key, 'color')"
      :title="get(data, key, 'title') || `title of ${key}`">
      <slot :name="key"></slot>
    </Window>
    <!-- lines -->
    <LeaderLine
      v-for="(item, index) in coordinates"
      :key="`coord_${index}`"
      :start="item.start" 
      :end="item.end"/>
  </Container>
</template>

<script>
// plugins
import shortid from 'shortid'
import resize from 'vue-resize-directive'

import Container from './Container'
import Cricle from './Cricle'
import Window from './Window'
import LeaderLine from './LeaderLine'

import element from '../utils/element'

export default {
  name: 'relationshipMap',
  directives: {
    resize,
  },
  components: {
    Container,
    Cricle,
    Window,
    LeaderLine
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      coordinates: [],
      slotKeys: [
        'leftTop',
        'top',
        'rightTop',
        'left',
        'center',
        'right',
        'leftBottom',
        'bottom',
        'rightBottom'
      ]
    }
  },
  computed: {
    ids () {
      const ids = {}
      this.slotKeys.forEach(key => {
        ids[key] = shortid.generate()
      })
      return ids
    },
    existSlots () {
      return Object.keys(this.$slots).filter(key => {
        return this.slotKeys.indexOf(key) !== -1 && key !== 'center'
      })
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.render()
    })
  },
  methods: {
    render () {
      this.coordinates = this.getLineCoord()
    },
    getLineCoord () {
      return this.existSlots.map(item => {
        return element(getNode(this.ids.center), getNode(this.ids[item]), item)
      })
    },
    get (data, slot, key) {
      return data && data[slot] && data[slot][key]
    },
    onResize () {
      this.render()
    }
  }
}

function getNode (id) {
  return document.querySelector(`[data-id="${id}"]`)
}
</script>

<style lang="scss">

</style>
